package com.smartao.base.menu;

import java.util.List;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.smartao.core.mvc.BaseAction;

@Controller
@Scope("prototype")
@Results({ @Result(name = "json", type="json", params={"root","menus"}), 
		@Result(name = "jsonSuccess", type="json", params={"root","message"}),
		@Result(name = "update", location="update.jsp"),
		@Result(name = "list", location="menu.jsp")})
public class MenuAction extends BaseAction{

	private static final long serialVersionUID = 8904201468812330656L;

	@Autowired
	private MenuService menuService;
	
	private List<Menu> menus;
	
	private Menu menu = new Menu();
	
	private String message = null;
	
	private MenuType menuType;
		
	@Override
	public String execute() throws Exception {
        return SUCCESS;
    }
	
	public String fetchSubMenus() throws Exception {
		menus = menuService.findSubMenuByMenutype(id, menuType);
		return JSON;
	}

	public String preUpdate(){
		if(id==null){
			menu = new Menu();
			menu.setMenutype(menuType);
			menu.setParent(new Menu());
		}
		else{
			menu = menuService.findOne(id);
		}
		return "update";
	}
	
	public String update(){
		if(menu.getParent()!=null && menu.getParent().getId()!=null){
			menu.setParent(menuService.findOne(menu.getParent().getId()));
		}
		else{
			menu.setParent(null);
		}
		menuService.save(menu);
		message = "保存成功!";
		return "update";
	}
	
	public String preAdd(){
		menu = new Menu();
		menu.setMenutype(menuType);
		if(id==null){
			menu.setParent(new Menu());
		}
		else{
			menu.setParent(menuService.findOne(id));
		}
		return "update";
	}
	
	public String delete(){
		if(id!=null){
			menuService.delete(id);
		}
		return SUCCESS;
	}
	
	public String updateVisibility(){
		menuService.updateVisibility(menu.getId(), menu.isVisible());
		return "jsonSuccess";
	}
	public List<Menu> getMenus() {
		return menus;
	}
	
	public Menu getMenu(){
		return menu;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public MenuType getMenuType() {
		return menuType;
	}

	public void setMenuType(MenuType menuType) {
		this.menuType = menuType;
	}
	
}
